package org.bulldog.playlist.notice;

import org.bulldog.playlist.PlayListBuilder;
import org.bulldog.playlist.util.DateUtil;

import java.util.*;

/**
 * Created by zhanghongbin on 2017/9/13.
 *
 * @author zhanghongbin
 * @version 1.0
 */
final class NoticePlayListBuilder implements PlayListBuilder<List<Notice>,Notice> {

    public static final int LIMIT_SECOND = 10;

    public static final NoticePlayListBuilder INSTANCE = new NoticePlayListBuilder();

    private final AscendingOrder ascendingOrder;

    private NoticePlayListBuilder() {
        ascendingOrder = new AscendingOrder();
    }


    @Override
    public List<Notice> build(List<Notice> noticeList) {
        String currentTime = DateUtil.now();
        String currentDate = currentTime.split(" ")[0] + " ";
        List<Notice> result = new ArrayList<>();
        String tempTime = currentTime;
        for (Notice notice : noticeList) {
            try {
                String startTime = currentDate + notice.getStartTime();
                String endTime = currentDate + notice.getEndTime();
                int n = DateUtil.minus(currentTime, endTime);
                if (n <= LIMIT_SECOND) {
                    continue;
                }
                int startIndex = DateUtil.compare(currentTime, startTime);
                notice.setStartTime(startTime);
                notice.setEndTime(endTime);
                notice.setDuration(DateUtil.minus(startTime, endTime));
                if (startIndex == 1 && n >= 0) {
                    notice.setPlayDuration(DateUtil.minus(currentTime, endTime) + LIMIT_SECOND);
                }
                if (startIndex == -1) {
                    Notice defaultNotice = new Notice("-1", "", tempTime, startTime);
                    defaultNotice.setDuration(DateUtil.minus(startTime, endTime));
                    result.add(defaultNotice);
                }
                tempTime = endTime;
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            result.add(notice);
        }
        if (!result.isEmpty()) {
            //升序排序
            Collections.sort(result, ascendingOrder);
        }
        return result;
    }

    private static class AscendingOrder implements Comparator<Notice> {

        @Override
        public int compare(Notice o1, Notice o2) {
            return DateUtil.compare(o1.getStartTime(), o2.getStartTime());
        }
    }

}
